package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class ExampleMain3 {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistStudent(emf);
        findStudentsByInnerJoinQuery(emf);
        emf.close();
    }

    private static void persistStudent(EntityManagerFactory emf){
        Task task1 = new Task("Coding","Denise");
        Task task2 = new Task("Refactoring","Rose");
        Task task3 = new Task("Designing","Denise");
        Task task4 = new Task("Documentation","Mike");

        Student student1 = Student.create("Diana",task1,task3);
        Student student2 = Student.create("Mike",task2,task4);
        Student student3 = Student.create("Tim",task3,task4);
        Student student4 = Student.create("Jack");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(student1);
        em.persist(student2);
        em.persist(student3);
        em.persist(student4);
        em.getTransaction().commit();
        em.close();
    }

    private static void findStudentsByInnerJoinQuery(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        String qlString1 = "select distinct s from Student s inner join s.tasks t";
        String qlString2 = "select distinct s from Student s inner join s.tasks t where t.supervisor = 'Denise'";
        String qlString3 = "select distinct s from Student s inner join s.tasks t where t.supervisor = s.name";
        String qlString4 = "select distinct s from Student s left outer join s.tasks t";
        Query query = em.createQuery(qlString4);
        List<Student> students = query.getResultList();
        for (Student student : students) {
            System.err.println(JSONObject.toJSONString(student,true));
        }
        em.close();
    }
}
